(function () {
  'use strict';

  angular
    .module('client')
    .controller('LoginController', LoginController);

  LoginController.$inject = ['$state', 'toastr', 'UserService', 'HTTP_STATUS_CODES'];
  function LoginController($state, toastr, UserService, HTTP_STATUS_CODES) {
    var vm = this;
    vm.credentials = {email: '', password: ''};
    vm.login = login;

    document.getElementById('email').onfocus = focus;
    document.getElementById('password').onfocus = focus;

    function focus() {
      vm.credentials[this.id] = this.value;
      this.onfocus = function () {}
    };

    function login(credentials) {
      UserService.login(credentials.email, credentials.password)
       .then(handleRequest, handleRequest);
    }

    function handleRequest(res) {
      if (HTTP_STATUS_CODES.OK === res.status) {
        $state.go('device');
      } else if (HTTP_STATUS_CODES.BAD_REQUEST === res.status) {
        toastr.error(res.data, '登陆失败')
      } else {
        toastr.error(res.statusText, '登陆失败');
      }
    }
  }
})();
